import os
import numpy as np
import matplotlib.pyplot as plt

def write_parser_input(quantiles, steps, filename):
    f=open(filename, "w")
    q = [str(qi) for qi in quantiles]
    f.write(','.join(q)+'\n')
    for s in steps:
        if(type(s) is list):
            st = [str(si) for si in s]
            f.write(','.join(st)+'\n')
        else:
            f.write(str(s)+'\n')
    f.close()



def icr_wrapper(inputname = 'testdata0.csv',mcmc_output = 'testdata.out',\
                   parsed_output = "testdata_parsed.out",\
                   parsed_input = "testdata_parsed.in",\
                   #run_it = False,parse_it = True, N=150, niter=3000, make=True,\
                   run_it = True,parse_it = True, N=150, niter=30000, make=True,\
                   quantiles=[0.1,0.5,0.9], steps = [[-3,3,0.25], [-5,5,0.05]], plot=False):
                   #quantiles=[0.1,0.5,0.9], steps = [1, [-5,5,0.05]], plot=True):
    '''
        inputname: name of the csv file that contains the data ('testdata0.csv')
        mcmc_output: name for the output of icr.cpp ('testdata.out')
        parsed_input: name of the file that controls the 
                      parser ('testdata_parsed.in')
        parsed_output: name of the file that the parser 
                       produces ('testdata_parsed.out')
        run_it: boolean for whether the modelling step should be run (True)
        parse_it: boolean for whether the evaluation step should be run (True)
        N: the number of components for DPM [50]
        niter: number of iterations [100]
        make: whether to recompile the code [True]
        quantiles: list of quantiles you want computed for each position on 
                   evaluation grid ([0.1,0.5,0.9])
        steps: list with one entry per dimension.  ([1, [-5,5,0.1]])
               Each entry is either
                  *a single numbers: interpreting as meaning this is 
                       observerd and output is conditioned on this
                  *a range of 3 numbers, interpreted as low,high, stepsize for
                       grid

        Written by R. da Silva, UCSC, 9-25-13
    '''
    print "should probably also set alpha priors"
    write_parser_input(quantiles, steps, parsed_input)
    if(make):
        os.system("make")
    tf = {}
    tf[True] = '1'
    tf[False] = '0'
    input_string = ("./icr " + inputname + " "+\
           mcmc_output + " " +\
           parsed_output + " "+\
           parsed_input + " "+\
           tf[run_it] + " "+\
           tf[parse_it]+ " " + str(N) + " " + str(niter))
    print input_string
    os.system(input_string)
    if plot == True:
        x = np.array(open('evalpts.txt').read().split('\n')[2:-1]).astype(float)
        y = np.array(open('output.txt').read().split('\n')[2:-1]).astype(float)
        plt.plot(x,y)
        plt.show()
        print "Normalization " +str(np.trapz(y,x=x))
        print "Center " +str(steps[0])

if __name__ == "__main__":
    icr_wrapper()
